import * as React from 'react';
import {
    authRely,
    util,
    IRouteComponentBaseProps,
    LOGIN_REDIRECT_KEY
} from '../index';

export class LogonCallback extends React.PureComponent<IRouteComponentBaseProps, any> {
    public static displayName = 'LogonCallback';

    constructor(props: IRouteComponentBaseProps) {
        super(props);
        this.state = {
            error: ''
        };
    }

    public async componentDidMount() {
        try {
            const tokens = await authRely.exchangeToken(util.getQueryString('code')!);
            // 保存 token
            authRely.saveToken(JSON.stringify(tokens));
            const userInfo = await authRely.getUserInfo(tokens.access_token);
            // 此处调整为同 electron 一致
            // 保存用户信息
            const newUserInfo = {
                openId: userInfo.open_id,
                userName: userInfo.UserName,
                rawInfo: userInfo
            };
            authRely.saveUser(JSON.stringify(newUserInfo));

            // 执行跳转
            let redirect = localStorage.getItem(LOGIN_REDIRECT_KEY);
            redirect = redirect || '/';
            localStorage.removeItem(LOGIN_REDIRECT_KEY);
            this.props.history.replace(redirect);

        } catch (err) {
            this.setState({
                error: err.message
            });
        }
    }

    public render() {
        return (
            <div>
                {
                    // tslint:disable-next-line:jsx-no-multiline-js
                    this.state.error.length === 0 ?
                        '登录成功，正在跳转...' :
                        <a href="javascript:void(0)" onClick={authRely.logout}>获取身份失败：{this.state.error}，请重新登录</a>
                }
            </div>
        );
    }
}
